package com.weitu.worklicense.controller;

import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.accessory.util.AccessoryUtil;
import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.contractor.service.ContractorAuditService;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.dataAuthority.service.DataAuthorityService;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import com.weitu.worklicense.entity.*;
import com.weitu.worklicense.service.LicenseMeasureService;
import com.weitu.worklicense.service.LimitLicenseService;
import com.weitu.worklicense.service.SafetyMeasuresService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * @author LiMeng 2017/6/9
 */
@Controller
@RequestMapping(value = "workLicense/limitLicense")
public class WorkLicenseLimitController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "workLicense/limitLicense";
    private static final String WORK_TYPE_ID = "699726d3a8be482589b6ec416e431c3d";
    private final LimitLicenseService limitLicenseService;
    private final SafetyMeasuresService safetyMeasuresService;
    private final LicenseMeasureService licenseMeasureService;
    private final ContractorAuditService contractorAuditService;
    private final DataAuthorityService dataAuthorityService;
    private final AccessoryUtilService accessoryUtilService;

    @Autowired
    public WorkLicenseLimitController(LimitLicenseService limitLicenseService
            , SafetyMeasuresService safetyMeasuresService
            , LicenseMeasureService licenseMeasureService
            , ContractorAuditService contractorAuditService
            , DataAuthorityService dataAuthorityService
            , AccessoryUtilService accessoryUtilService) {
        this.limitLicenseService = limitLicenseService;
        this.safetyMeasuresService = safetyMeasuresService;
        this.licenseMeasureService = licenseMeasureService;
        this.contractorAuditService = contractorAuditService;
        this.dataAuthorityService = dataAuthorityService;
        this.accessoryUtilService = accessoryUtilService;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() {
        return MODULE_BATH_PATH + "/list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute("workTypeId", WORK_TYPE_ID);
        return MODULE_BATH_PATH + "/add";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, String id) {
        putModelAttributes(model, id);
        return MODULE_BATH_PATH + "/edit";
    }

    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(Model model, String id) {
        putModelAttributes(model, id);
        return MODULE_BATH_PATH + "/view";
    }

    @RequestMapping(value = "/copy", method = RequestMethod.GET)
    public String copy(Model model, String id) {
        putModelAttributes(model, id);
        return MODULE_BATH_PATH + "/copy";
    }

    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public Object listAjax(HttpServletRequest request, String sort) {
        LimitLicenseCriteria criteria = new LimitLicenseCriteria();
        LimitLicenseCriteria.Criteria cr = criteria.createCriteria()
                .andDelStateEqualTo(0);
        putSearchCriteria(cr);

        int count = limitLicenseService.countByCriteria(criteria);
        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        //未传sort参数是采用添加时间排序
        if (StringUtils.isEmpty(sort)) {
            pageView.setSortColumn("addTime");
        } else {
            criteria.setOrderByClause(pageView.getSortColumn() + " " + pageView.getOrderType());
        }
        criteria.setPageView(pageView);

        List<LimitLicense> limitLicenses = limitLicenseService.selectByCriteria(criteria);
        return dataGridPagination.flushDataGridData(limitLicenses);
    }

    @SystemLog(module = "受限空间作业许可办理", methods = "新增受限空间作业许可信息")
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @Transactional
    public AjaxResult addAjax(LimitLicense limitLicense, String safeMeasures) {
        String id = IDGenerator.getId();
        limitLicense.setId(id);
        limitLicense.setCode(DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS"));
        addCreateAttribute(limitLicense);
        if (AccessoryUtil.saveAccerssoryInfo(id)) {
            if (limitLicenseService.insertSelective(limitLicense) > 0) {
                if (StringUtils.isNotEmpty(safeMeasures)) {
                    saveMeasures(safeMeasures, id);
                }
                return success("保存成功！", limitLicense);
            } else {
                return fail("附件保存失败！");
            }
        } else {
            return fail("保存失败！");
        }
    }

    @SystemLog(module = "受限空间作业许可办理", methods = "修改受限空间作业许可信息")
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public AjaxResult editAjax(LimitLicense limitLicense) {
        String id = limitLicense.getId();
        addUpdateAttribute(limitLicense);
        if (AccessoryUtil.saveAccerssoryInfo(id)) {
            if (limitLicenseService.updateByPrimaryKeySelective(limitLicense) > 0) {
                return success("保存成功！", limitLicense);
            } else {
                return fail("附件保存失败！");
            }
        } else {
            return fail("保存失败！");
        }
    }

    @SystemLog(module = "受限空间作业许可办理", methods = "删除受限空间作业许可信息")
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult deleteAjax(String id) {
        if (limitLicenseService.deleteByPrimaryKey(id) > 0) {
            return success("删除成功！");
        } else {
            return fail("删除失败！");
        }
    }

    @SystemLog(module = "受限空间作业许可办理", methods = "执行受限空间作业许可信息")
    @ResponseBody
    @RequestMapping(value = "/execute", method = RequestMethod.POST)
    public AjaxResult executeAjax(String id) {
        LimitLicense limitLicense = new LimitLicense();
        limitLicense.setId(id);
        limitLicense.setAuditState(1);
        if (limitLicenseService.updateByPrimaryKeySelective(limitLicense) > 0) {
            return success("执行成功！");
        } else {
            return fail("执行失败！");
        }
    }

    /**
     * 添加登记人、登记时间和部门信息
     *
     * @param entity 实体
     */
    private void addCreateAttribute(LimitLicense entity) {
        entity.setAddUserId(getSessionUser().getId());
        entity.setAddDeptId(getSessionUser().getDepartment().getId());
        entity.setAddTime(DateTimeUtil.formatterDateTime());
        entity.setAddUserName(getSessionUser().getRealName());
        entity.setAddDeptName(getSessionUser().getDepartment().getName());
    }

    /**
     * 添加修改人、修改时间和部门信息
     *
     * @param entity 实体
     */
    private void addUpdateAttribute(LimitLicense entity) {
        entity.setUpdateUserId(getSessionUser().getId());
        entity.setUpdateUserName(getSessionUser().getName());
        entity.setUpdateDeptId(getSessionUser().getDepartment().getId());
        entity.setUpdateDeptName(getSessionUser().getDepartment().getName());
        entity.setUpdateTime(DateTimeUtil.formatterDateTime());
    }

    /**
     * 添加查询条件
     *
     * @param criteria 条件
     */
    private void putSearchCriteria(LimitLicenseCriteria.Criteria criteria) {
        if (getParaToInt("auditState") != null) {
            criteria.andAuditStateEqualTo(getParaToInt("auditState"));
        }
        if (StringUtils.isNotEmpty(getPara("applyUserId"))) {
            criteria.andAddUserIdEqualTo(getPara("applyUserId"));
        }
        if (StringUtils.isNotEmpty(getPara("applyDeptId"))) {
            criteria.andAddDeptIdEqualTo(getPara("applyDeptId"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMin"))) {
            criteria.andAddTimeGreaterThanOrEqualTo(getPara("addTimeMin"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMax"))) {
            criteria.andAddTimeLessThanOrEqualTo(getPara("addTimeMax"));
        }
        if (StringUtils.isNotEmpty(getPara("addUserId"))) {
            criteria.andAddUserIdEqualTo(getPara("addUserId"));
        }
        if (StringUtils.isNotEmpty(getPara("addDeptId"))) {
            criteria.andAddDeptIdEqualTo(getPara("addDeptId"));
        }
        List<String> deptIds = dataAuthorityService.selectDataDeptIdByUserIdAndDeptId(getSessionUser().getId()
                , getSessionUser().getDepartment().getId());
        if (!deptIds.isEmpty()) {
            criteria.andAddDeptIdIn(deptIds);
        }
    }

    /**
     * 向页面实体添加属性
     *
     * @param model 页面实体
     * @param id    主键id
     */
    private void putModelAttributes(Model model, String id) {
        model.addAttribute("workTypeId", WORK_TYPE_ID);
        LimitLicense limitLicense = limitLicenseService.selectByPrimaryKey(id);
        model.addAttribute("accessoryList", accessoryUtilService.queryAccessoryByBusinessId(id));
        model.addAttribute("limitLicense", limitLicense);
        if (StringUtils.isNotEmpty(limitLicense.getContractorAuditId())) {
            String contractorId = contractorAuditService.selectByPrimaryKey(limitLicense.getContractorAuditId()).getContractorId();
            model.addAttribute("contractorId", contractorId);
        }
        LicenseMeasureCriteria example = new LicenseMeasureCriteria();
        example.createCriteria().andLicenseIdEqualTo(id);
        List<LicenseMeasure> licenseMeasures = licenseMeasureService.selectByCriteria(example);
        if (licenseMeasures != null && !licenseMeasures.isEmpty()) {
            String measureId = licenseMeasures.get(0).getMeasureId();
            SafetyMeasures safetyMeasure = safetyMeasuresService.selectByPrimaryKey(measureId);
            if (safetyMeasure != null) {
                String safeMeasures = safetyMeasure.getContent();
                model.addAttribute("safeMeasures", safeMeasures);
            }
        }
    }

    /**
     * 保存安全措施
     *
     * @param safeMeasures 安全措施内容
     * @param id           许可id
     */
    private void saveMeasures(String safeMeasures, String id) {
        // TODO: 2017/6/5 暂时插入单条安全措施,以后插入多条
        SafetyMeasures safetyMeasure = new SafetyMeasures();
        LicenseMeasure licenseMeasure = new LicenseMeasure();
        String safeMeasureId = IDGenerator.getId();
        safetyMeasure.setId(safeMeasureId);
        safetyMeasure.setAddUserId(getSessionUser().getId());
        safetyMeasure.setAddDeptId(getSessionUser().getDepartment().getId());
        safetyMeasure.setAddTime(DateTimeUtil.formatterDateTime());
        safetyMeasure.setContent(safeMeasures);
        safetyMeasure.setTypeId(WORK_TYPE_ID);
        safetyMeasure.setTypeName("受限空间作业");
        licenseMeasure.setId(IDGenerator.getId());
        licenseMeasure.setLicenseId(id);
        licenseMeasure.setMeasureId(safeMeasureId);
        safetyMeasuresService.insertSelective(safetyMeasure);
        licenseMeasureService.deleteByLicenseId(id);
        licenseMeasureService.insertSelective(licenseMeasure);
    }
}
